using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.DAL;
using AcctrueWMS.Foundation.Common.Exception;
using System.Web;
using AcctrueWMS.Foundation.DAL;

namespace AcctrueWMS.Foundation.Web
{
    class CommonFunction
    {
        /// <summary>
        /// 删除通用方法
        /// </summary>
        /// <param name="keyValueExpress">主键值表达式,例如:[orderNo=123]|[orderNo=456]</param>
        /// <param name="modelName">模板名称</param>
        /// <returns>返回操作状态</returns>
        public string  CommonDeleteDate(string keyValueExpress,string  modelName)
        {
            string ifSuccess = "FAL";
            DataModelKeyValue tbList = DataModelManager.GetDataModelKeyValue(modelName);
            if (string.IsNullOrEmpty(keyValueExpress)) return ifSuccess;
            string delSQL = string.Empty;
            string[] keyValues = keyValueExpress.Split('|');
            string valueList = string.Empty;
            foreach (string keyValue in keyValues)
            {
                valueList += keyValue.Split('=')[1] + ",";
            }
            if (!string.IsNullOrEmpty(valueList)) valueList = valueList.Substring(0, valueList.Length - 1);
            using (IDbConnection conn = DBFactory.NewConnection())
            {
                conn.Open();
                IDbTransaction tran = conn.BeginTransaction();
                //删除主表
                delSQL = string.Format("delete from  {0}  where {1} in ('{2}')",tbList.TableName,tbList.KeyColumnName,valueList.Replace(",", "','"));
                WMSqlExcuter.ExecuteNonQuery(tran, delSQL, CommandType.Text);
                //删除关联表
                foreach (DataModelKeyValue tbDetail in tbList.DetailKeyValues)
                {
                    delSQL = string.Format(" delete from  {0}  where {1} in ('{2}') ", tbDetail.TableName, tbDetail.KeyColumnName, valueList.Replace(",", "','"));
                    WMSqlExcuter.ExecuteNonQuery(tran, delSQL, CommandType.Text);
                }
                tran.Commit();
                ifSuccess = "OK";
            }
            return ifSuccess;
        }

        /// <summary>
        /// 带联合主键的删除通用方法
        /// </summary>
        /// <param name="keyValueExpress">主键值表达式,例如:materialCode=6000*batchNo=0N000004*depotWBS=010104|materialCode=6000*batchNo=BN000001*depotWBS=010101</param>
        /// <param name="modelName">模板名称</param>
        /// <returns>返回操作状态</returns>
        public string CommonDeleteRecords(string keyValueExpress, string modelName)
        {
            string ifSuccess = "FAL";
            DataModelKeyValue tbList = DataModelManager.GetDataModelKeyValue(modelName);
            if (string.IsNullOrEmpty(keyValueExpress)) return ifSuccess;
            string delSQL = string.Empty;
            string[] keyValues = keyValueExpress.Split('|');
            foreach (string keyValue in keyValues)
            {
                string[] conditions = keyValue.Split('*');
                string where = "";
                foreach (string condition in conditions)
                {
                    where += condition.Split('=')[0] + "='" + condition.Split('=')[1]  + "' and ";
                }
                where += " 1=1";
                delSQL += string.Format("delete from  {0}  where {1};\r\n", tbList.TableName, where);
            }

            using (IDbConnection conn = DBFactory.NewConnection())
            {
                conn.Open();
                IDbTransaction tran = conn.BeginTransaction();
                //删除主表
                WMSqlExcuter.ExecuteNonQuery(tran, delSQL, CommandType.Text);
                tran.Commit();
                ifSuccess = "OK";
            }
            return ifSuccess;
        }

        /// <summary>
        /// 删除上传的文档
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>返回执行结果   OK 表示删除成功</returns>
        public string DelFile(string filePath)
        {
            filePath = CommonFunction.UnEscape(filePath);

            //删除物理文件
            try
            {
                string extName = (string)WMSqlExcuter.ExecuteScalar("SELECT extName FROM sys_attachments WHERE filePath = @filePath",
                   CommandType.Text,
                   DBFactory.NewParameter("filePath", filePath));
                string uploadPath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + System.Configuration.ConfigurationManager.AppSettings["uploadFilePath"].ToString());
                System.IO.File.Delete(uploadPath + "/" + filePath + extName);
            }
            catch { }

            //删除系统记录
            string sSql = string.Format("delete FROM sys_attachments WHERE filePath = '{0}'", filePath);
            WMSqlExcuter.ExecuteNonQuery(sSql, CommandType.Text);
            return "OK";
        }

        /// <summary>
        /// Escape的解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <returns>返回解密之后的字符串</returns>
        public static string UnEscape(string str)
        {
            if (str == null)
                return String.Empty;

            StringBuilder sb = new StringBuilder();
            int len = str.Length;
            int i = 0;
            while (i != len)
            {
                if (Uri.IsHexEncoding(str, i))
                    sb.Append(Uri.HexUnescape(str, ref i));
                else
                    sb.Append(str[i++]);
            }

            return sb.ToString();
        }
		//获取GUID
        public string CreateGUID()
        {
            return Guid.NewGuid().ToString();
        }

    }
}
